﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
using DailyDiet.Models;
using DailyDiet.Services.Constant;

namespace DailyDiet.Services.Impl
{
    /// <summary>
    /// 缓存类 采用序列化的方式缓存一个对象
    /// 使用步骤：
    ///     1.在CacheSerializeConstant中注入一个key，并指定key对应的文件地址
    ///     2.将需要缓存的对象放入一个Cache对象进行包装
    ///     3.调用SerializeAsync方法序列化缓存对象
    ///     4.调用DeSerializeAsync方法反序列缓存对象
    /// </summary>
    public class CacheSerializeService : ICacheSerializeService
    {
        private BinaryFormatter _serializer;

        public BinaryFormatter Serializer =>
            _serializer ?? (_serializer = new BinaryFormatter());

        private static readonly string _filePath =
            Environment.GetFolderPath(Environment.SpecialFolder
                .LocalApplicationData);

        /// <summary>
        /// 序列化方法
        /// </summary>
        /// <typeparam name="T">泛型-需要序列化的对象类型</typeparam>
        /// <param name="cache">需要序列化的对象-对象需要使用Cache包装一下</param>
        /// <param name="cacheKey">缓存key，改建需要提前在CacheSerializeConstant中注册</param>
        /// <returns></returns>
        public async Task SerializeAsync<T>(Cache<T> cache, string cacheKey) {
            string fileName = CacheSerializeConstant.KeyToFileName[cacheKey];

            using (var fileStream = new FileStream(Path.Combine(_filePath, fileName), FileMode.OpenOrCreate))
            {
                try
                {
                    Serializer.Serialize(fileStream, cache);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    throw;
                }
            }
        }

        /// <summary>
        /// 反序列化
        /// </summary>
        /// <typeparam name="T">反序列化得到对象的类型</typeparam>
        /// <param name="cacheKey">缓存key，也就是序列化的时候用的什么key反序列化就用什么key</param>
        /// <returns></returns>
        public async Task<Cache<T>> DeSerializeAsync<T>(string cacheKey) {
            string fileName = CacheSerializeConstant.KeyToFileName[cacheKey];
            if (!File.Exists(Path.Combine(_filePath, fileName))) {
                return null;
            }
            using (FileStream fileStream =
                new FileStream(Path.Combine(_filePath, fileName), FileMode.OpenOrCreate))
            {
                Cache<T> cache =
                    Serializer.Deserialize(fileStream) as Cache<T>;
                return cache;
            }
        }
    }
}
